import { getCommentAddAPI, getCommentInfoAPI } from '@/api/comment'
import './index.scss'
import { Avatar, Button, List, Drawer, message, Modal, Empty  } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { useEffect, useState } from 'react'

import {  getReplyAddAPI, getReplyInfoAPI } from '@/api/reply'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'

const BlogComment = (props) => {
    // eslint-disable-next-line react/prop-types
    const { open, closeDrawer, blogId } = props
    const onClose = (value) => {
        closeDrawer(value)
    }

    // 获取评论列表
    const [commentList, setCommentList] = useState([])
    const getCommentList = async () => {
      const res = await getCommentInfoAPI(blogId)
      setCommentList(res.data)
    }

    // 获取回复列表
    const [replyList, setReplyList] = useState([])
    // let replyInfo = []
    const getReplyList = async () => {
      const promises = commentList.map(async (item) => {
        const res = await getReplyInfoAPI(item.id);
        return res.data;
      });
      const allReplies = await Promise.all(promises);
      const mergedReplies = allReplies.flat(); // 将所有回复合并成一个数组
      setReplyList(mergedReplies);
    }
    useEffect(() => {
      const fetchData = async () => {
        try {
          const commentRes = await getCommentInfoAPI(blogId);
          setCommentList(commentRes.data);
    
          // 获取所有评论的回复列表
          const replyPromises = commentRes.data.map(async (comment) => {
            const res = await getReplyInfoAPI(comment.id);
            return res.data;
          });
          const allReplies = await Promise.all(replyPromises);
          const mergedReplies = allReplies.flat();
          setReplyList(mergedReplies);
        } catch (error) {
          // 处理错误
        }
      };
    
      fetchData();
    }, [])

    // 新增评论
    const [commentText, setCommentText] = useState('')
    const userInfo = useSelector(state => state.user.userInfo)
    const subComment = async () => {
      const res = await getCommentAddAPI({username: userInfo.username, blogId, text: commentText })
      if (res.code === 1) {
        message.success('评论成功')
        setCommentText('')
        getCommentList()
      }
    }
    // 新增回复
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [replyId, setReplyId] = useState()
  const [replyText, setReplyText] = useState('')

  const showDrawer = (id) => {
    setReplyId(id)
    setIsModalOpen(true)
  }
  const handleCancel = () => {
    setIsModalOpen(!isModalOpen)
  }
    const  subReply = async () => {
      if (replyText) {
        setConfirmLoading(true)
        const res = await getReplyAddAPI({username: userInfo.username, commentId:replyId, text: replyText })
        if (res.code === 1) {
          message.success('回复成功')
          setReplyText('')
          setIsModalOpen(false)
          getReplyList()
          setConfirmLoading(false)
        }
      } else 
       message.warning('请输入回复内容')
    }
    return (
      <div className="comment">
        <Drawer
          title="评论详情"
          width={600}
          onClose={() => onClose(false)}
          open={open}
        >
          <div className="sub-comment">
            <TextArea
              size='large'
              placeholder='发表一条友善的评论吧'
              allowClear
              showCount 
              maxLength={300}
              value={commentText} 
              onChange={(e) => setCommentText(e.target.value)} >
            </TextArea>
            <Button
              className='sub-btn' 
              type='primary' 
              size='small'
              onClick={subComment}
              >
                发表
            </Button>
          </div>
          { commentList && commentList.length ?
            <List
              itemLayout="vertical"
              size="large"
              dataSource={commentList}
              renderItem={(item) => (
                <List.Item
                  key={item.id}>                
                <div className="header">
                  <span onClick={() => showDrawer(item.id)} style={{float: 'right', cursor: 'pointer' }}>回复</span>
                  <List.Item.Meta
                    avatar={<Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=8" />}
                    title={item.username}
                    description={`发表时间：${dayjs(item.createTime).format('YYYY-MM-DD')} `}
                  />
                </div>
                <div className="text">
                  <span>{item.text}</span>
                </div>
                <Modal 
                  title="回复详情" 
                  okText="确认"
                  cancelText='取消'
                  open={isModalOpen} 
                  confirmLoading={confirmLoading}
                  onOk={subReply} 
                  onCancel={handleCancel}>
                  <TextArea value={replyText} onChange={(e) => setReplyText(e.target.value)}></TextArea>
                </Modal>
                {replyList.filter(reply => reply.commentId === item.id).length
                ? 
                <List
                  className='reply-list'
                  itemLayout="vertical"
                  size="large"
                  dataSource={replyList.filter(reply => reply.commentId === item.id)}
                  renderItem={(item) => (
                    <List.Item
                      key={item.id}
                    >
                      <div className="header">
                        <List.Item.Meta
                          avatar={<Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=8" />}
                          title={item.username}
                          description={`回复时间：${dayjs(item.createTime).format('YYYY-MM-DD')} `}
                        />
                      </div>
                      <div className="text">
                        <span>{item.text}</span>
                      </div>
                    </List.Item>
                  )}
                /> : <div></div>
              }
              </List.Item>
            )}
          />
        : <div>
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      </div> }
      </Drawer>
    </div>
  )
}

export default BlogComment